package com.zwb.service.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zwb.service.common.CacheConstant;
import com.zwb.service.dto.MenusRoleDto;
import com.zwb.service.pojo.Menu;
import com.zwb.service.pojo.MenuRole;
import com.zwb.service.pojo.Role;
import com.zwb.service.service.IMenuRoleService;
import com.zwb.service.service.IMenuService;
import com.zwb.service.service.IRoleService;
import com.zwb.service.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 头发又黑又长
 * @Date 2022/9/2 14:07
 * @email zwb15083976291@163.com
 */
@Api(tags = "权限管理")
@RestController
@CacheConfig(cacheNames = CacheConstant.CACHEABLE_VALUE_3_DAT)
@RequestMapping("/system/basic/permission")
public class PermissionController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IMenuRoleService menuRoleService;
    @Autowired
    private IMenuService menuService;

    @Cacheable(key = "'roleAll'")
    @ApiOperation("获取所有角色")
    @GetMapping("/")
    public R getRoleAll() {
        return R.success(roleService.list());
    }


    @ApiOperation("添加角色")
    @CacheEvict(key = "'roleAll'")
    @PostMapping("/")
    public R addRole(@RequestBody Role role) {
        if (!role.getName().startsWith("ROLE_")) {
            role.setName("ROLE_" + role.getName());
        }
        return roleService.save(role) ? R.success("添加角色成功") : R.error("添加角色失败");
    }

    @ApiOperation("删除角色")
    @CacheEvict(key = "'roleAll'")
    @DeleteMapping("/{id}")
    public R delRole(@PathVariable("id") Long id) {
        return roleService.removeById(id)
                ? R.success("删除角色成功") : R.error("删除角色失败");
    }

    @ApiOperation("查询所有菜单")
    @GetMapping("/menu")
    @Cacheable(key = "'menuAll'")
    public R getMenus() {
        List<Menu> menus = menuService.getMenusAll();
        return R.success(menus);
    }


    @ApiOperation("根据角色id查询菜单")
    @GetMapping("/mid/{rid}")
    public R<List<Integer>> getMidByRid(@PathVariable("rid") Long rid) {
        List<Integer> collect = menuRoleService.list(
                new LambdaQueryWrapper<MenuRole>().eq(MenuRole::getRid, rid)
        ).stream().map(MenuRole::getMid).collect(Collectors.toList());
        return R.success(collect);
    }


    @ApiOperation("更新角色信息")
    @PutMapping("/")
    public R updateMenuRole(@RequestBody MenusRoleDto menusRoleDto) {
        menuRoleService.updateMenusRole(menusRoleDto);
        return R.success("更新角色信息成功");
    }

}
